package com.weijun.keepalive_daemon.receiver

import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import java.util.LinkedList

/**
 * @author: weijun
 * date: 2023/7/6
 * description: 屏幕状态监听
 */
object ScreenStatusManager {

    private lateinit var mScreenReceiver :ScreenBroadcastReceiver
    val mObservers = LinkedList<Observer>()

    fun addObserver(observer: Observer) = mObservers.add(observer)
    fun removeObserver(observer: Observer) = mObservers.remove(observer)

    fun register(context: Context) {
        if (::mScreenReceiver.isInitialized.not()) {
            mScreenReceiver = ScreenBroadcastReceiver()
        }
        context.registerReceiver(mScreenReceiver, IntentFilter().apply {
            addAction(Intent.ACTION_SCREEN_ON)
            addAction(Intent.ACTION_SCREEN_OFF)
            addAction(Intent.ACTION_USER_PRESENT)
        })
    }

    fun unregister(context: Context) {
        try {
            if (::mScreenReceiver.isInitialized) {
                context.unregisterReceiver(mScreenReceiver)
            }
        }catch(ignore:Exception) { }
    }

    interface Observer {
        fun screenStatusChanged(screenOn:Boolean)
    }
}